// 做一个保存数据的方法
const mongoose = require('mongoose');
const { Schema } = mongoose;
mongoose.connect('mongodb://localhost:27017/animal', { useNewUrlParser: true, useUnifiedTopology: true });
// 这里创建一个人类表的约束
const PeopleSchema = new Schema({
  type: { type: String },
  name: { type: String, default: '' },//有默认值的属性再插入时不添加会自动以默认值插入
  age: { type: Number },
  sex: { type: String, default: '男' },
  height: { type: Number },
  date: { type: Date, default: Date.now },
});

//第一个参数为字符串，mongodb会在连接的数据库中创建一个以这个字符串命名的表名，第二个参数为这个表的约束条件及所含字段
const People = mongoose.model('People', PeopleSchema);

// 添加数据
exports.add = function (type, name, age, sex, height) {
  if (type === 'student') {
    const student = new People({
      type,
      name,
      age,
      sex,
      height
    })
    student.save().then(() => console.log('学生信息保存成功'));

  }
  else if (type === 'teacher') {
    const teacher = new People({
      type,
      name,
      age,
      sex,
      height
    })
    teacher.save().then(() => console.log('老师信息数据保存成功'));
  }
}
// 搜索数据

exports.search = function (type, callback) {

  People.find({
    type
  }, function (err, res) {
    if (err) {
      console.log(err)
    }
    else {
      callback(res)
    }
  })

}